package com.econage.eccm.test.base.webdatasource.rsa;


import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

public final class RSACryptoUtils {
    private RSACryptoUtils() {
    }

    private static final String BUILTIN_PUB_KEY_BASE64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn66SpTdPpnDz4/gIZ7Y9gmbc41dwGPq31UFvAlqb7hy67CojqcP+GKrC/U9OiuRP4Tll5o0EQbuvvRWG8BCP/+OUCQZAVlUXHOU5zECp/wZZAkLlrX/1bihr5+eKQptlLFN6rVIeAhlCQFqb90zkHx4X9MROMRrve5ZNGOAWeHOVrDnTsrksHafls9LA7zxbEXRyBGWsbyAV6DgMcINwEVnnOhKVbGwd+fybqPNfkT95UrEFKVsfBtU38hTephpOdMoMyAMVAWl18/flGe6qnrxqTDS95YXdsLQGNxq0NWPm11aGsDjcc943XbGuWIILIyibGaToUyXmUqkgYmLENQIDAQAB";

    /**
     * String转公钥PublicKey
     * @param key
     * @return RSAPublicKey
     */
    public static RSAPublicKey parsePublicKeyBase64(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.base64ToByteArray(key));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey)keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA公钥解密
     *
     * @param content 加密字符串
     * @return 明文
     */
    public static String rsaDecryptByPubKey(String content) throws Exception {
        RSAPublicKey publicKey = parsePublicKeyBase64(BUILTIN_PUB_KEY_BASE64);

        byte[] orgContentByte = Base64.base64ToByteArray(content);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return new String(cipher.doFinal(orgContentByte), StandardCharsets.UTF_8);
    }


}
